package com.ruoyi.house.utils;

import com.ruoyi.house.enums.DeviceType;
import org.springframework.web.servlet.ModelAndView;

public class ModelAndViewUtil {
	/**
	 * Prefix for special view names that specify a redirect URL (usually
	 * to a controller after a form has been submitted and processed).
	 */
	private static final String REDIRECT_URL_PREFIX = "redirect:";

	/**
	 * Prefix for special view names that specify a forward URL (usually
	 * to a controller after a form has been submitted and processed).
	 */
	private static final String FORWARD_URL_PREFIX = "forward:";
	
	/**
	 * 手机视图前缀
	 */
	private static String mobilePrefix = "/mobile/";
	
	/**
	 * PC视图前缀
	 */
	private static String normalPrefix = "/front/";

	
	public static ModelAndView of(String viewName) {
		ModelAndView mv = new ModelAndView();

		// Check for special "redirect:" prefix.
		if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
			mv.setViewName(viewName);
			return mv;
		}
		// Check for special "forward:" prefix.
		if (viewName.startsWith(FORWARD_URL_PREFIX)) {
			mv.setViewName(viewName);
			return mv;
		}

		DeviceType deviceType = WebUtils.getDeviceType();
		String resolvedViewName;
		if (deviceType.isMobile()) {
			resolvedViewName = mobilePrefix + viewName;
		}
		else {
			resolvedViewName = normalPrefix + viewName;
		}

		mv.setViewName(resolvedViewName);
		return mv;
	}
	
	public static ModelAndView of(String pcViewName, String mobileViewName) {
		ModelAndView mv = new ModelAndView();

		DeviceType deviceType = WebUtils.getDeviceType();
		String viewName;
		if (deviceType.isMobile()) {
			viewName = mobileViewName;
		}
		else {
			viewName = pcViewName;
		}

		// Check for special "redirect:" prefix.
		if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
			mv.setViewName(viewName);
			return mv;
		}
		
		// Check for special "forward:" prefix.
		if (viewName.startsWith(FORWARD_URL_PREFIX)) {
			mv.setViewName(viewName);
			return mv;
		}

		String resolvedViewName;
		if (deviceType.isMobile()) {
			resolvedViewName = mobilePrefix + mobileViewName;
		}
		else {
			resolvedViewName = normalPrefix + pcViewName;
		}

		mv.setViewName(resolvedViewName);
		return mv;
	}

}
